<template>
  <view class="page-container">
    <!-- 顶部区域 -->
    <view class="page-header">
      <text class="greeting"> {{ hello }} </text>
      <view class="right-box">
        <view class="new-project-btn material-price-btn" @click="showMaterialPriceModal">
          主材价：{{ PriceTime }}
        </view>
        <view class="new-project-btn batch-btn" @click="showBatchCreateModal">
          批量创建项目
        </view>
        <view class="new-project-btn" @click="openModal">
          {{ up === 1 ? '新建项目' : '项目确认' }}
        </view>
        <view class="new-project-btn" @click="logout">注销</view> 
      </view>
    </view>

    <!-- 主体内容区域 -->
    <view class="page-content">
      <view class="left-pane">
        <TableComponent
          ref="tableComponent"
          :data="tableData"
        />
      </view>
      <view class="right-pane">
        <DashboardComponent ref="dashboardComponent" />
      </view>
    </view>

    <uni-popup ref="Modal" type="center">
      <view v-if="up === 1" class="modal-content">
        <view class="modal-title">上传结算表</view>
        <view class="upload-hint">点击上传：仅支持excel表格，注意制表规范</view>
        <view class="upload-area" @click="chooseAndUploadFile">
          <uni-icons type="plusempty" size="50" color="#007aff" />
        </view>
        <button class="modal-close" @click="closeModal">关闭</button>
      </view>
      <view v-else-if="up === 2" class="modal-content">
        <view class="modal-title">新建项目确认</view>
        <view class="info-container">
          <view class="info-row">
            <text class="info-label">项目名称：</text>
            <text class="info-value">{{ return_data.proj_name }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">站点名称：</text>
            <text class="info-value">{{ return_data.task_name }}</text>
          </view>
          <view class="info-row">
            <text class="info-label">项目经理：</text>
            <text v-if="is_need_approv" class="info-value">{{ user }}</text>
            <view v-else class="manager-selector">
              <view class="selected-managers" @click="showManagerPicker">
                <text v-if="selectedManagers.length === 0" class="placeholder">请选择项目经理</text>
                <view v-else class="manager-tags">
                  <view 
                    v-for="(manager, index) in selectedManagers" 
                    :key="index" 
                    class="manager-tag"
                  >
                    <text class="manager-name">{{ manager }}</text>
                    <text class="remove-btn" @click.stop="removeManager(index)">×</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view v-if="is_need_approv" class="info-row">
            <text class="info-label">审批人：</text>
            <picker
              mode="selector"
              :range="approverOptions"
              :value="selectedApprover"
              @change="onApproverChange"
            >
              <view class="picker-view">
                {{
                  selectedApprover === -1
                    ? "请选择"
                    : approverOptions[selectedApprover]
                }}
              </view>
            </picker>
          </view>
        </view>
        <view class="upload-hint">上传图纸文件</view>
        <view class="upload-area" @click="chooseAndUploadFile">
          <uni-icons type="plusempty" size="50" color="#007aff" />
        </view>
        <button class="modal-close" @click="closeModal">关闭</button>
      </view>
    </uni-popup>

    <!-- 批量创建项目模态框 -->
    <BatchCreateProjectModal 
      :visible="showBatchModal" 
      :personsData="personsData"
      @close="showBatchModal = false"
      @success="handleBatchCreateSuccess"
    />

    <!-- 主材价格管理模态框 -->
    <uni-popup ref="MaterialPriceModal" type="center">
      <view class="modal-content">
        <view class="modal-title">主材价格管理</view>
        
        <!-- 当前价格表信息 -->
        
        <view class="upload-hint">上传最新主材价格PDF文件</view>
        <view class="upload-area" @click="chooseAndUploadMaterialPriceFile">
          <uni-icons type="plusempty" size="50" color="#007aff" />
        </view>
        
        <button class="modal-close" @click="closeMaterialPriceModal">关闭</button>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from "vue";
import DashboardComponent from "@/components/DashboardComponent.vue";
import TableComponent from "@/components/TableComponent.vue";
import BatchCreateProjectModal from "@/components/BatchCreateProjectModal.vue";

const user = uni.getStorageSync("userInfo").name;
const role = uni.getStorageSync("userInfo").role;
const token = uni.getStorageSync("userInfo").token;
if (!token) {
  uni.showToast({
    title: '请先登录',
    icon: 'none',
    duration: 2000
  })
  uni.redirectTo({
    url: "/pages/login",
  });
}else{
  uni.request({
    url: './api/ct',
    method: 'GET',
    header: {
      'Authorization': `Bearer ${token}`
    },
    success: (res) => {
      if (!(res.statusCode === 200 && res.data.message === "合法")) {
        uni.showToast({
          title: '请先登录',
          icon: 'none',
          duration: 2000
        })
        uni.redirectTo({
          url: "/pages/login",
        });
      }
    }
  })
}

const logout = () => {
  // 清除本地存储的用户信息
  uni.removeStorageSync('userInfo'); 
  // 跳转登录页面
  uni.redirectTo({
    url: '/pages/login',
  });
};

// 判断当前时间是上午、下午还是晚上
const getGreeting = () => {
  const hour = new Date().getHours();
  if (hour < 12) return "早上好，";
  if (hour < 18) return "下午好，";
  return "晚上好，";
};

const greeting = ref(getGreeting());
const hello = ref(greeting.value + user);
const PriceTime = ref('');

// 移除视图切换功能，固定为项目视图

// 表格数据
const tableData = reactive([]);

function handleSubmit(payload) {
  tableData.push({ name: payload.name, age: payload.age });
}

// 模态框逻辑
const Modal = ref(null);

const openModal = () => {
  // 如果是第一次打开或者需要重新开始，重置状态
  if (up.value === 1) {
    return_data.value = {};
    selectedManagers.value = [];
    selectedApprover.value = -1;
    // console.log('打开模态框，开始新流程，up值为:', up.value);
  } else {
    // console.log('打开模态框，继续项目确认流程，up值为:', up.value);
  }
  Modal.value.open();
};

const closeModal = () => {
  // 关闭时不重置up值，只有在完成整个流程后才重置
  // up.value = 1; // 移除这行，让up值保持当前状态
  // return_data.value = {}; // 保留数据，用户可能需要重新打开继续操作
  selectedManagers.value = [];
  selectedApprover.value = -1;
  // console.log('关闭模态框，up值保持为:', up.value);
  Modal.value.close();
};

const isUploading = ref(false);
const up = ref(1);
const return_data = ref({});
const is_need_approv = ref(role != "rose2");

// 项目经理选项
const managerOptions = ref([]);
const approverOptions = ref([]);
// 当前选中的项目经理数组
const selectedManagers = ref([]);
const selectedApprover = ref(-1);

// 批量创建项目相关
const showBatchModal = ref(false);
const personsData = ref({});

// 主材价格管理相关
const MaterialPriceModal = ref(null);
const materialPriceInfo = ref('');
const isUploadingMaterialPrice = ref(false);

// 显示主材价格管理模态框
const showMaterialPriceModal = () => {
  MaterialPriceModal.value.open();
};

// 关闭主材价格管理模态框
const closeMaterialPriceModal = () => {
  MaterialPriceModal.value.close();
};

// 选择并上传主材价格PDF文件
const chooseAndUploadMaterialPriceFile = () => {
  uni.chooseFile({
    count: 1,
    extension: [".pdf"],
    success: (res) => {
      const file = res.tempFiles[0];
      isUploadingMaterialPrice.value = true;
      uni.showLoading({
        title: "上传中...",
        mask: true,
      });

      uni.uploadFile({
        url: './api/catch_price',
        filePath: file.path,
        name: "file",
        header: {
          Authorization: `Bearer ${token}`,
        },
        success: (uploadRes) => {
          if (uploadRes.statusCode == 200) {
            const result = JSON.parse(uploadRes.data);
            if (result.success) {
              uni.showToast({ title: "上传成功", icon: "success" });
              materialPriceInfo.value = result.info;
              // 刷新价格表信息
              fetchMaterialPriceInfo();
            } else {
              uni.showToast({
                title: result.message || "上传失败",
                icon: "none"
              });
            }
          } else {
            uni.showToast({
              title: "上传失败",
              icon: "none"
            });
          }
        },
        fail: (err) => {
          console.error("上传失败", err);
          uni.showToast({ title: "上传失败", icon: "none" });
        },
        complete: () => {
          isUploadingMaterialPrice.value = false;
          uni.hideLoading();
        },
      });
    },
    fail: (err) => {
      console.error("选择文件失败", err);
      uni.showToast({ title: "选择失败", icon: "none" });
    },
  });
};

// 显示项目经理选择器
const showManagerPicker = () => {
  uni.showActionSheet({
    itemList: managerOptions.value,
    success: (res) => {
      const selectedManager = managerOptions.value[res.tapIndex];
      // 检查是否已经选择过该项目经理
      if (!selectedManagers.value.includes(selectedManager)) {
        selectedManagers.value.push(selectedManager);
      } else {
        uni.showToast({
          title: "该项目经理已选择",
          icon: "none"
        });
      }
    }
  });
};

// 移除项目经理
const removeManager = (index) => {
  selectedManagers.value.splice(index, 1);
};

const onApproverChange = (e) => {
  selectedApprover.value = e.detail.value;
  // // console.log('选中的审批人是：', approverOptions.value[selectedApprover.value]);
};

// 显示批量创建项目模态框
const showBatchCreateModal = () => {
  showBatchModal.value = true;
};

// 处理批量创建项目成功
const handleBatchCreateSuccess = () => {
  // 刷新表格和看板数据
  tableComponent.value?.fetchData();
  dashboardComponent.value?.refreshData();
  
  uni.showToast({
    title: '批量创建项目成功',
    icon: 'success'
  });
};

const tableComponent = ref(null);
const dashboardComponent = ref(null);

const chooseAndUploadFile = () => {
  // 问题3：当需要选择项目经理时，如果没有选择项目经理就要上传图纸，不允许
  if (up.value === 2 && !is_need_approv.value && selectedManagers.value.length === 0) {
    uni.showToast({ title: "请先选择项目经理", icon: "none" });
    return;
  }

  uni.chooseFile({
    count: 1,
    extension: [".xls", ".xlsx", ".pdf"],
    success: (res) => {
      const file = res.tempFiles[0];
      isUploading.value = true;
      uni.showLoading({
        title: "上传中...",
        mask: true,
      });

      const apiUrl = up.value === 1 ? "./api/upload" : "./api/updraw";
      const formData = {};
      if (role === "rose2") {
        selectedApprover.value = 0;
      }

      if (up.value === 2) {
        if (selectedApprover.value === -1) {
          uni.showToast({ title: "请先选择审批人", icon: "none" });
          isUploading.value = false;
          uni.hideLoading();
          return;
        }
        if (is_need_approv.value) {
          formData.projectManager = user;
        } else {
          // 将多个项目经理用英文逗号连接
          formData.projectManager = selectedManagers.value.join(',');
        }
        formData.approver = approverOptions.value[selectedApprover.value];
        formData.projID = return_data.value.proj_id;
        formData.taskID = return_data.value.task_id;
      }

      uni.uploadFile({
        url: apiUrl,
        filePath: file.path,
        name: "file",
        formData,
        header: {
          Authorization: `Bearer ${token}`,
        },
        success: (uploadRes) => {
        console.log(file.path,formData)
          if (uploadRes.statusCode == 200) {
            if (up.value === 1) {
              return_data.value = JSON.parse(uploadRes.data);
              up.value = 2;
              // console.log('第一步上传成功，up值变为:', up.value);
              // console.log('返回数据:', return_data.value);
              // 第一步完成后不关闭模态框，直接切换到项目确认界面
              // Modal.value.close(); // 移除这行，保持模态框打开状态
            } else if (up.value === 2) {
              uni.showToast({ title: "上传成功", icon: "success" });
              // 只有在第二步完成后才重置所有状态
              up.value = 1;
              return_data.value = {};
              selectedManagers.value = [];
              selectedApprover.value = -1;
              // console.log('第二步上传成功，完整流程结束，up值重置为:', up.value);
              Modal.value.close();
              // 刷新表格和看板数据
              tableComponent.value?.fetchData();
              dashboardComponent.value?.refreshData();
            }
          } else {
            uni.showToast({
              title: JSON.parse(uploadRes.data).message,
              icon: "fail",
            });
          }
        },
        fail: (err) => {
          console.error("上传失败", err);
          uni.showToast({ title: "上传失败", icon: "fail" });
        },
        complete: () => {
          isUploading.value = false;
          uni.hideLoading();
        },
      });
    },
    fail: (err) => {
      console.error("选择文件失败", err);
      uni.showToast({ title: "选择失败", icon: "fail" });
    },
  });
};

const personOptions = ref(["全部"]);

const fetchPersonOptions = () => {
  uni.request({
    url: "./api/persons",
    method: "GET",
    header: {
      Authorization: `Bearer ${token}`,
    },
    success: (res) => {
      // console.log('获取人员数据:', res.data);
      if (typeof res.data === "object" && res.data !== null) {
        // 保存原始数据供批量创建项目使用
        personsData.value = res.data;
        
        let all = [];
        for (const [dept, persons] of Object.entries(res.data)) {
          if (Array.isArray(persons)) {
            all.push(...persons.map((p) => `${dept}-${p}`));
          }
        }
        managerOptions.value = all.filter((item) => item !== "全部");
        approverOptions.value = all.filter((item) => item.includes("工建"));
        all.sort();
        personOptions.value = ["全部", ...all];
        // console.log('项目经理选项:', managerOptions.value);
        // console.log('审批人选项:', approverOptions.value);
        // console.log('原始人员数据:', personsData.value);
      } else {
        console.error('人员数据格式不正确:', res.data);
        personOptions.value = ["全部"];
        managerOptions.value = [];
        approverOptions.value = [];
        personsData.value = {};
      }
    },
    fail: (err) => {
      console.error('获取人员数据失败:', err);
      personOptions.value = ["全部"];
      managerOptions.value = [];
      approverOptions.value = [];
    },
  });
};

const fetchPriceTime = () => {
  uni.request({
    url: "./api/priceTime",
    method: "GET",
    header: {
      Authorization: `Bearer ${token}`,
    },
    success: (res) => {
      if (res.data !== null) {
        PriceTime.value = res.data;
      } else {
        console.error('价格数据格式不正确:', res.data);
      }
    },
    fail: (err) => {
      console.error('获取价格数据失败:', err);
    },
  });
}

onMounted(() => {
  fetchPersonOptions();
  fetchPriceTime();
  // 问题2：监听删除事件，刷新数据看板
  uni.$on('refreshDashboard', () => {
    dashboardComponent.value?.refreshData();
  });
});

onUnmounted(() => {
  // 移除事件监听器
  uni.$off('refreshDashboard');
});
</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 95vh;
  background-color: #f0f2f5;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    "Helvetica Neue", Arial, sans-serif;
}

/* 顶部 Header 区 */
.page-header {
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.greeting {
  font-size: 1.75rem;
  color: #333;
  font-weight: 500;
}

/* 右侧按钮区域样式 */
.right-box {
  display: flex;
  align-items: center;
  gap: 16px; /* 按钮之间的间距 */
}

.new-project-btn {
  background-color: #127ae2be;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  white-space: nowrap;
  cursor: pointer; 
}

.batch-btn {
  background-color: #28a745;
}

.batch-btn:hover {
  background-color: #218838;
}

.material-price-btn {
  background-color: #ff9800;
}

.material-price-btn:hover {
  background-color: #f57c00;
}

/* 主体区域：左右两栏 */
.page-content {
  flex: 1;
  display: grid;
  grid-template-columns: 3fr 1fr;
  gap: 24px;
  padding: 0 24px 24px;
  box-sizing: border-box;
  overflow: hidden;
}

.left-pane,
.right-pane {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: auto;
}

/* Modal 部分 */
.modal-content {
  background: white;
  padding: 40rpx;
  border-radius: 20rpx;
  width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.modal-title {
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 30rpx;
  text-align: center;
}
.upload-hint {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 30rpx;
  text-align: center;
}
.upload-area {
  height: 200rpx;
  border: 2rpx dashed #127ae2be;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 122, 255, 0.05);
  transition: all 0.3s;
}
.upload-area:active {
  background-color: rgba(0, 122, 255, 0.1);
}
.modal-close {
  margin-top: 30rpx;
  background: #127ae2be;
  color: white;
  border-radius: 8rpx;
  height: 42px;
}
.info-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 30rpx;
}

.info-row {
  display: flex;
  align-items: center;
}

.info-label {
  font-size: 26rpx;
  color: #666;
  width: 180rpx;
}

.info-value {
  font-size: 26rpx;
  color: #333;
  flex: 1;
}

/* 项目经理选择器样式 */
.manager-selector {
  flex: 1;
}

.selected-managers {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 8px;
  min-height: 40px;
  background-color: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.placeholder {
  color: #999;
  font-size: 26rpx;
}

.manager-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  width: 100%;
}

.manager-tag {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 16px;
  padding: 4px 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 24rpx;
}

.manager-name {
  color: #1890ff;
}

.remove-btn {
  color: #ff4d4f;
  font-weight: bold;
  cursor: pointer;
  font-size: 18px;
  line-height: 1;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: rgba(255, 77, 79, 0.1);
}

.remove-btn:hover {
  background-color: rgba(255, 77, 79, 0.2);
}
</style>